<?php

include_once APPPATH . '/models/fly_search/air_pricing_solution.php';
include_once APPPATH . '/models/fly_search/journey.php';
include_once APPPATH . '/models/fly_search/air_pricing_info.php';
include_once APPPATH . '/models/fly_search/air_segment.php';
include_once APPPATH . '/models/fly_search/travelport_low_search_response.php';
include_once APPPATH . '/models/fly_search/flight_detail.php';
include_once APPPATH . '/models/fly_search/book_info.php';
include_once APPPATH . '/models/fly_search/fly_search_criteria.php';
include_once APPPATH . '/models/fly_search/combined_air_price_solution.php';
include_once APPPATH . '/models/constants/flight_constants.php';
include_once APPPATH . '/services/airline_service.php';

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Travelport
 *
 * @author pasa
 */
class Travelport {

    public static $instance;

    public function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new Travelport();
        }
        return self::$instance;
    }

    private function sendMessageTravelportApi($message) {
        //file_put_contents("low_fare_search_request.xml", $message);

        $CREDENTIALS = 'Universal API/uAPI8206124988:mbg39cXEgndKhCS96m7phxwbh';
        $auth = base64_encode("$CREDENTIALS");
        $soap_do = curl_init("https://americas.copy-webservices.travelport.com/B2BGateway/connect/uAPI/AirService");
// $message = $this->buildLowFareAirSearchMessage($search_criteria);
        $header = array(
            "Content-Type: text/xml;charset=UTF-8", "Accept: gzip,deflate",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "SOAPAction: \"\"",
            "Authorization: Basic $auth",
            "Content-length: " . strlen($message),
        );
        curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 300);
        curl_setopt($soap_do, CURLOPT_TIMEOUT, 300);
        curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($soap_do, CURLOPT_POST, true);
        curl_setopt($soap_do, CURLOPT_SSLVERSION, 3);
        curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($soap_do, CURLOPT_POSTFIELDS, $message);
        curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
        return $result_xml = curl_exec($soap_do);
    }

    public function searchFlights($search_criteria) {
        $request_soap_message = $this->buildLowFareAirSearchMessage($search_criteria);
        return $this->sendMessageTravelportApi($request_soap_message);
    }

    public function getFareRule() {
        
    }

    private function buildLowFareAirSearchMessage($search_criteria) {

        $TARGETBRANCH = 'P105231';

        $message = <<<EOM
        <s:Envelope xmlns:s = "http://schemas.xmlsoap.org/soap/envelope/">
        <s:Body xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
        <LowFareSearchReq xmlns="http://www.travelport.com/schema/air_v22_0" TargetBranch="$TARGETBRANCH">
        <BillingPointOfSaleInfo OriginApplication = "UAPI" xmlns = "http://www.travelport.com/schema/common_v19_0" ></BillingPointOfSaleInfo>
EOM;
        $message = $message . ($this->buildAirSearchLeg($search_criteria, $search_criteria->boardingCode, $search_criteria->landingCode, $search_criteria->godate));
        if ($search_criteria->flydirection == 2) {
            $message = $message . ($this->buildAirSearchLeg($search_criteria, $search_criteria->landingCode, $search_criteria->boardingCode, $search_criteria->returndate));
        }
        $flight_type_message = $this->buidFlightTypeMessage($search_criteria);
        $message = $message . <<<EOM
        <AirSearchModifiers>
        <PreferredProviders>
        <Provider Code = "1G" xmlns = "http://www.travelport.com/schema/common_v19_0" ></Provider>
        </PreferredProviders>
          $flight_type_message
        </AirSearchModifiers>
EOM;
        $message = $message . $this->buildPassangerOption($search_criteria->yetiskinnumber, $search_criteria->cocuknumber, $search_criteria->bebeknumber);
        $message = $message . $this->buildAirPricingModifier($search_criteria);
        $message .= <<<EOM
                </LowFareSearchReq>
            </s:Body>
        </s:Envelope>
EOM;
        return $message;
    }

    private function buildAirSearchLeg($search_criteria, $origin_airport_code, $destination_airport_code, $preferred_time) {
        $preferred_time = $preferred_time . "T00:00:00";
        $airleg_modifier_messagge = $this->buildAirLegModifier($search_criteria);

        $message = <<<EOM
        <SearchAirLeg>
        <SearchOrigin>
        <CityOrAirport Code = "$origin_airport_code" xmlns = "http://www.travelport.com/schema/common_v19_0" ></CityOrAirport>
        </SearchOrigin>
        <SearchDestination>
        <CityOrAirport Code = "$destination_airport_code" xmlns = "http://www.travelport.com/schema/common_v19_0" ></CityOrAirport>
        </SearchDestination>
        <SearchDepTime PreferredTime = "$preferred_time" ></SearchDepTime>
          $airleg_modifier_messagge
        </SearchAirLeg>
EOM;
        return $message;
    }

    private function buildAirLegModifier($search_criteria) {
        $cabinclass_mesage = null;
        $flight_type_message = null;
        if (isset($search_criteria->cabinclass) && $search_criteria->cabinclass != "all") {
            $cabinclass_mesage = <<<EOM
         <PreferredCabins>
             <CabinClass Type = "$search_criteria->cabinclass" ></CabinClass>
        </PreferredCabins>
EOM;
        }
        $flight_type_message = $this->buidFlightTypeMessage($search_criteria);

        $message = <<<EOM
        <AirLegModifiers>
          $cabinclass_mesage
          $flight_type_message
        </AirLegModifiers>
EOM;
        return $message;
    }

    private function buidFlightTypeMessage($search_criteria) {
        if ($search_criteria->flighttype == "all") {
            return "";
        }

//for non-stop flights
        if ($search_criteria->flighttype == "1") {
            $message = <<<EOM
                    <FlightType  RequireSingleCarrier="true" MaxConnections="0" MaxStops="0" />
EOM;
            return $message;
        }
        return "";
    }

    private function buildPassangerOption($yetiskin_number, $cocuk_number, $bebek_number) {
        $message = "";
        for ($i = 0; $i < (int) $yetiskin_number; $i++)
            $message .= '<SearchPassenger xmlns = "http://www.travelport.com/schema/common_v19_0" PricePTCOnly="false" Code="ADT"/>';

        for ($i = 0; $i < (int) $cocuk_number; $i++)
            $message .= '<SearchPassenger xmlns = "http://www.travelport.com/schema/common_v19_0" PricePTCOnly="false"  Age="7" Code="CNN"/>';

        for ($i = 0; $i < (int) $bebek_number; $i++)
            $message .= '<SearchPassenger xmlns = "http://www.travelport.com/schema/common_v19_0" PricePTCOnly="false" Code="INF"/>';

        return $message;
    }

    private function buildAirPricingModifier($search_criteria) {
        $message = <<<EOM
                 <AirPricingModifiers CurrencyType="$search_criteria->currency"></AirPricingModifiers>
EOM;
        return $message;
    }

    public function parseLowFareSearchTravelPortApi($responseXmlData = null, $search_criteria) {
        if (!isset($responseXmlData)) {
            return null;
        }

        $xml = new SimpleXMLElement($responseXmlData);
        $xml->formatOutput = true;
        $xml->registerXPathNamespace('air', 'http://www.travelport.com/schema/air_v22_0');
        $travelport_low_search_response = new TravelPortLowSearchResponse();
        $air_price_solution_arrays = array();
        foreach ($xml->xpath('//air:AirPricingSolution') as $air_price_solution_item) {
            $air_price_solution_object = new AirPricingSolution();
            $air_price_solution_item_attributes = $air_price_solution_item->attributes();
            $air_price_solution_object->key = (string) $air_price_solution_item_attributes["Key"][0];
            $air_price_solution_object->total_price = (string) $air_price_solution_item_attributes["TotalPrice"][0];
            $air_price_solution_object->base_price = (string) $air_price_solution_item_attributes["BasePrice"][0];
            $air_price_solution_object->apprixomate_total_price = (string) $air_price_solution_item_attributes["ApproximateTotalPrice"][0];
            $air_price_solution_object->approximate_base_price = (string) $air_price_solution_item_attributes["ApproximateBasePrice"][0];
            $air_price_solution_object->equivalent_base_price = (string) $air_price_solution_item_attributes["EquivalentBasePrice"][0];
            $air_price_solution_object->taxes = (string) $air_price_solution_item_attributes["Taxes"][0];
            preg_match('/([^a-zA-Z]+)/', $air_price_solution_object->apprixomate_total_price, $total_price_match);
            $air_price_solution_object->apprixomate_total_price_amount = $total_price_match[0];

            preg_match('/([^a-zA-Z]+)/', $air_price_solution_object->taxes, $tax_price_match);
            $air_price_solution_object->taxes_amount = $tax_price_match[0];
            $air_price_solution_object->air_pricing_info = $this->airPriceInfoXMLToObject($air_price_solution_item);
            //$this->airPriceInfoXMLToObject($air_price_solution_item);
            $air_price_solution_object->journeys = $this->airJourneyXMLToObject($air_price_solution_item, $search_criteria);

            array_push($air_price_solution_arrays, $air_price_solution_object); 
        }
        $travelport_low_search_response->air_price_solutions = $air_price_solution_arrays;
        $air_segment_arrays = array();
        foreach ($xml->xpath('//air:AirSegment') as $air_segment_item) {
            $air_segment_object = $this->airSegmentXMLToObject($air_segment_item);
            array_push($air_segment_arrays, $air_segment_object);
        }
        $flight_detail_arrays = array();
        foreach ($xml->xpath('//air:FlightDetails') as $flight_detail_item) {
            array_push($flight_detail_arrays, $this->flightDetailXMLToObject($flight_detail_item));
        }
        $travelport_low_search_response->flight_details = $flight_detail_arrays;
        $travelport_low_search_response->air_segments = $air_segment_arrays;
        return $travelport_low_search_response;
    }

    public function airPriceInfoXMLToObject($air_price_solution_item = null) {
        $air_price_info_object_list = array();
        foreach ($air_price_solution_item->children('air', TRUE) as $air_price_solution_item_node) {
            if ($air_price_solution_item_node->getName() == "AirPricingInfo") {
                $air_price_info_item = $air_price_solution_item_node;
                $air_price_info_item_attributes = $air_price_info_item->attributes();
                $air_price_info_object = new AirPricingInfo();
                $air_price_info_object->key = (string) $air_price_info_item_attributes["Key"][0];
                $air_price_info_object->approximate_base_price = (string) $air_price_info_item_attributes["ApproximateBasePrice"];
                $air_price_info_object->approximate_total_price = (string) $air_price_info_item_attributes["ApproximateTotalPrice"][0];
                $air_price_info_object->taxes = (string) $air_price_info_item_attributes["Taxes"][0];

                $air_price_info_object->lastest_ticketing_time = (string) $air_price_info_item_attributes["LatestTicketingTime"][0];
                $air_price_info_object->platin_carrier = (string) $air_price_info_item_attributes["PlatingCarrier"][0];
                $air_price_info_object->refundable = (string) $air_price_info_item_attributes["Refundable"][0];
                preg_match('/([^a-zA-Z]+)/', $air_price_info_object->approximate_base_price, $base_price_match);
                $air_price_info_object->approximate_base_price_amount = $base_price_match[0];
                preg_match('/([^a-zA-Z]+)/', $air_price_info_object->approximate_total_price, $total_price_match);
                $air_price_info_object->approximate_total_price_amout = $total_price_match[0];
                preg_match('/([^a-zA-Z]+)/', $air_price_info_object->taxes, $tax_price_match);
                $air_price_info_object->taxes_amount = $tax_price_match[0];

                $booking_info_array = array();
                $passenger_count = 0;
                foreach ($air_price_solution_item_node->children('air', TRUE) as $air_price_solution_child_node) {
                    $air_price_solution_child_node_attributes = $air_price_solution_child_node->attributes();
                    if ($air_price_solution_child_node->getName() === "PassengerType") {
                        $air_price_info_object->passenger_type = (string) $air_price_solution_child_node_attributes["Code"][0];
                        if ($air_price_info_object->passenger_type == "ADT") {
                            $air_price_info_object->passenger_type_desc = "Yetişkin";
                        } else if ($air_price_info_object->passenger_type == "CNN") {
                            $air_price_info_object->passenger_type_desc = "Çocuk";
                        } else if ($air_price_info_object->passenger_type == "INF") {
                            $air_price_info_object->passenger_type_desc = "Bebek";
                        } else {
                            $air_price_info_object->passenger_type_desc = $air_price_info_object->passenger_type;
                        }

                        $passenger_count++;
                    } else if ($air_price_solution_child_node->getName() === "BookingInfo") {
                        $booking_info_object = new BookingInfo();
                        $booking_info_object->air_segment_ref = (string) $air_price_solution_child_node_attributes["SegmentRef"][0];
                        $booking_info_object->booking_code = (string) $air_price_solution_child_node_attributes["BookingCode"][0];
                        $booking_info_object->cabin_class = (string) $air_price_solution_child_node_attributes["CabinClass"][0];
                        $booking_info_object->fare_info_ref = (string) $air_price_solution_child_node_attributes["FareınfoRef"][0];

                        array_push($booking_info_array, $booking_info_object);
                    }
                }
                $air_price_info_object->passenger_count = $passenger_count;
                $air_price_info_object->booking_short_info_array = $booking_info_array;
                array_push($air_price_info_object_list, $air_price_info_object);
            }
        }
        return $air_price_info_object_list;
    }

    public function airJourneyXMLToObject($air_price_solution_item = null, $search_criteria) {
        $air_journey_items = array();
        $air_price_solution_item_attributes = $air_price_solution_item->attributes();
        $journey_count = 0;
        foreach ($air_price_solution_item->children('air', TRUE) as $air_price_solution_item_node) {
            if ($air_price_solution_item_node->getName() === "Journey") {
                $air_price_solution_item_node_attributes = $air_price_solution_item_node->attributes();
                $journey_object = new Journey();
                $journey_object->key = Fly_seach_helper::create_unique_solution_key();
                $journey_object->travel_time = (string) $air_price_solution_item_node_attributes["TravelTime"][0];
                $journey_object->total_travel_time = $this->convert_journey_travel_time($journey_object->travel_time);
                $air_segment_key_refs = array();

                foreach ($air_price_solution_item_node->children('air', TRUE) as $journey_child_item_node) {
                    if ($journey_child_item_node->getName() === "AirSegmentRef") {
                        $journey_child_item_node_attributes = $journey_child_item_node->attributes();
                        array_push($air_segment_key_refs, (string) $journey_child_item_node_attributes["Key"][0]);
                    }
                }
                $journey_object->air_segment_keys = $air_segment_key_refs;
                $journey_object->air_price_solution_key_ref = (string) $air_price_solution_item_attributes["Key"][0];
                if ($search_criteria->flydirection == 2 && $journey_count == 1) {
                    $journey_object->type = Fly_Constant::RETURN_JOURNEY_TYPE;
                } else {
                    $journey_object->type = Fly_Constant::DEPARTURE_JOURNEY_TYPE;
                }
                $journey_count++;
                array_push($air_journey_items, $journey_object);
            }
        }
        return $air_journey_items;
    }

//<air:AirSegment Key="1T" Group="0" Carrier="TK" FlightNumber="1958" Origin="AMS" Destination="IST" DepartureTime="2013-03-30T14:50:00.000+01:00" ArrivalTime="2013-03-30T19:20:00.000+02:00" FlightTime="210" Distance="1384" ETicketability="Yes" Equipment="738" ChangeOfPlane="false" ParticipantLevel="Secure Sell" LinkAvailability="true" PolledAvailabilityOption="Polled avail exists" OptionalServicesIndicator="false" AvailabilitySource="AvailStatusTTY">
    /**
      <air:CodeshareInfo OperatingCarrier="LO" OperatingFlightNumber="270"/>
      <air:AirAvailInfo ProviderCode="1G">
      <air:BookingCodeInfo BookingCounts="C3|D2|Z1|IL|Y9|B9|M9|E9|H9|K9|Q9|G9|T8|S3|XL|VL|WC|LC|UC|OC"/>
      </air:AirAvailInfo>
      <air:FlightDetailsRef Key="19T"/>

     */
    private function airSegmentXMLToObject($air_segment_item) {
        $air_segment_item_attributes = $air_segment_item->attributes();
        $air_segment_object = new AirSegment();
        $air_segment_object->key = (string) $air_segment_item_attributes["Key"][0];
        $air_segment_object->carrier = (string) $air_segment_item_attributes["Carrier"][0];
        $air_segment_object->carrierName = AirlineService::getAirlineByIATACode($air_segment_object->carrier)->name;
        $air_segment_object->flight_number = (string) $air_segment_item_attributes["FlightNumber"][0];
        $air_segment_object->origin = (string) $air_segment_item_attributes["Origin"][0];
        $air_segment_object->destination = (string) $air_segment_item_attributes["Destination"][0];
        $air_segment_object->departure_time = (string) $air_segment_item_attributes["DepartureTime"][0];
        $air_segment_object->arrival_time = (string) $air_segment_item_attributes["ArrivalTime"][0];
        $air_segment_object->flight_time = (string) $air_segment_item_attributes["FlightTime"][0];
        $air_segment_object->distance = (string) $air_segment_item_attributes["Distance"][0];
        $air_segment_object->equipment = (string) $air_segment_item_attributes["Equipment"][0];
        $air_segment_object->eticket_avability = (string) $air_segment_item_attributes["ETicketability"][0];
        foreach ($air_segment_item->children('air', TRUE) as $air_segment_child_item) {
            $air_segment_child_item_attributes = $air_segment_child_item->attributes();
            if ($air_segment_child_item->getName() === "FlightDetailsRef") {
                $air_segment_object->flight_ref = (string) $air_segment_child_item_attributes["Key"][0];
            } else if ($air_segment_child_item->getName() == "AirAvailInfo") {
                $air_segment_object->provider_code = (string) $air_segment_child_item_attributes["ProviderCode"][0];
                foreach ($air_segment_child_item->children('air', TRUE) as $child) {
                    if ($child->getName() === "BookingCodeInfo") {
                        $child_attributes = $child->attributes();
                        $air_segment_object->booking_counts = (string) $child_attributes["BookingCounts"][0];
                    }
                }
            }
        }
        return $air_segment_object;
    }

    /*
      <air:FlightDetails Key="2T" Origin="AMS" Destination="FRA" DepartureTime="2013-03-30T19:40:00.000+01:00"
     * ArrivalTime="2013-03-30T20:50:00.000+01:00" FlightTime="70" Equipment="735" DestinationTerminal="1"/>
     */

    private function flightDetailXMLToObject($flight_detail_item) {
        $flight_detail_item_attributes = $flight_detail_item->attributes();
        $flight_detail_object = new FlightDetail();
        $flight_detail_object->key = (string) $flight_detail_item_attributes["Key"][0];
        $flight_detail_object->origin = (string) $flight_detail_item_attributes["Origin"][0];
        $flight_detail_object->destination = (string) $flight_detail_item_attributes["Destination"][0];
        $flight_detail_object->departure_time = (string) $flight_detail_item_attributes["DepartureTime"][0];
        $flight_detail_object->arrival_time = (string) $flight_detail_item_attributes["ArrivalTime"][0];
        $flight_detail_object->flight_time = (string) $flight_detail_item_attributes["FlightTime"][0];
        $flight_detail_object->origin_terminal = (string) $flight_detail_item_attributes["OriginTerminal"][0];
        $flight_detail_object->destination_terminal = (string) $flight_detail_item_attributes["DestinationTerminal"][0];
        return $flight_detail_object;
    }

    public function combineAirPriceSolutions($travelport_low_search_response) {


        $combined_air_price_solutions_array = array();
        $air_price_solutions = $travelport_low_search_response->air_price_solutions;
        $price_air_price_solution_map_array = array();
        
        foreach ($air_price_solutions as $air_price_solution_item) {
            $count = 0;
            
            if(isset($price_air_price_solution_map_array[$air_price_solution_item->apprixomate_total_price])){
                   $combined_air_price_solutions =  $price_air_price_solution_map_array[$air_price_solution_item->apprixomate_total_price];
                   array_push($combined_air_price_solutions, $air_price_solution_item);
                   $price_air_price_solution_map_array[$air_price_solution_item->apprixomate_total_price] =  $combined_air_price_solutions;
                           
            }else {
                  $combined_air_price_solutions = array();
                  array_push($combined_air_price_solutions, $air_price_solution_item);
                  $price_air_price_solution_map_array[$air_price_solution_item->apprixomate_total_price] =  $combined_air_price_solutions;
            }
        }
         foreach($price_air_price_solution_map_array as  $combined_air_price_solutions) { 
                $combined_air_price_solution_item = new CombinedAirPriceSolution();
                $combined_air_price_solution_item->apprixomate_total_price = $combined_air_price_solutions[0]->apprixomate_total_price;
                $combined_air_price_solution_item->apprixomate_total_price_amount = $combined_air_price_solutions[0]->apprixomate_total_price_amount;
                $combined_air_price_solution_item->approximate_base_price = $combined_air_price_solutions[0]->approximate_base_price;
                $combined_air_price_solution_item->taxes_amount = $combined_air_price_solutions[0]->taxes_amount;
                $combined_air_price_solution_item->taxes = $combined_air_price_solutions[0]->taxes;
                $combined_air_price_solution_item->air_price_info_items = $combined_air_price_solutions[0]->air_pricing_info;
                $combined_air_price_solution_item->combined_key = Fly_seach_helper::create_unique_solution_key();

                $departure_journeys = array();
                $return_journeys = array();
                $departure_journeys_unique_keys = array();
                $return_journeys_unique_keys = array();
                foreach ($combined_air_price_solutions as $combined_air_price_solution) {
                    $departure_journey = null;
                    $return_journey = null;
                    $is_exist_departure_journey = FALSE;
                    $is_exist_return_journey = FALSE;
                    $unique_departure_journey_key = "";
                    $unique_return_journey_key = "";
                    $departure_journey_air_company = Fly_Constant::COMBINATION_AIR_COMPANY;
                    $return_journey_air_company = Fly_Constant::COMBINATION_AIR_COMPANY;
                    
                    //$related_journey_id; 
                    foreach ($combined_air_price_solution->journeys as $journey) {
                        if ($journey->type == Fly_Constant::DEPARTURE_JOURNEY_TYPE) {
                            $departure_journey = $journey;
                        } else if ($journey->type == Fly_Constant::RETURN_JOURNEY_TYPE) {
                            $return_journey = $journey;
                        }
                    }

                 if ($departure_journey != null) {
                     
                        $unique_departure_journey_key = $this->create_journey_uniqe_key($departure_journey->air_segment_keys);
                        $is_exist_departure_journey = $this->isExsistAirsegmentKey($departure_journeys_unique_keys, $unique_departure_journey_key);
                        $air_segment_objects = $this->gets_airsegment_by_keys($departure_journey->air_segment_keys, $travelport_low_search_response->air_segments);
                        foreach($air_segment_objects as $air_segment_object){
                            $air_segment_object = $this->set_booking_info_to_airsegment_project($combined_air_price_solution->air_pricing_info, $air_segment_object);
                        }
                        $departure_journey->air_segment_items = $air_segment_objects; 
                        
                        $departure_journey_air_company = $this->get_airline_company_of_journey($departure_journey);
                        $departure_journey->air_price_solution_key_ref = $combined_air_price_solution->key;
                        
                    }

                    if ($return_journey != null) {
                         $unique_return_journey_key = $this->create_journey_uniqe_key($return_journey->air_segment_keys);
                         $is_exist_return_journey = $this->isExsistAirsegmentKey($return_journeys_unique_keys, $unique_return_journey_key);
                         $air_segment_objects = $this->gets_airsegment_by_keys($return_journey->air_segment_keys, $travelport_low_search_response->air_segments);
                           foreach($air_segment_objects as $air_segment_object){
                            $air_segment_object = $this->set_booking_info_to_airsegment_project($combined_air_price_solution->air_pricing_info, $air_segment_object);
                        }
                        $return_journey->air_segment_items = $air_segment_objects; 
                        $return_journey_air_company = $this->get_airline_company_of_journey($return_journey);
                        $return_journey->air_price_solution_key_ref = $combined_air_price_solution->key;
                    }

                    if (!$is_exist_departure_journey && !$is_exist_return_journey) {
                        if ($return_journey != null) {
                            $return_journey->related_journey_id = $unique_departure_journey_key;
                            $departure_journey->related_journey_id = $unique_departure_journey_key;
                        }
                    } else if (!$is_exist_departure_journey && $is_exist_return_journey) {
                           $departure_journey->related_journey_id = $unique_return_journey_key;
                           $return_journey->related_journey_id = $unique_return_journey_key;
                    } else if ($is_exist_departure_journey && !$is_exist_return_journey) {
                        if ($return_journey != null) {
                            $return_journey->related_journey_id = $unique_departure_journey_key;
                            $departure_journey->related_journey_id = $unique_departure_journey_key;
                        }
                    }
                    
                    if(!$is_exist_departure_journey && $departure_journey != null){
                           $departure_journey->key =  $unique_departure_journey_key;
                           if($return_journey != null){
                               if($departure_journey_air_company == $return_journey_air_company){
                                   $departure_journey->air_company = $departure_journey_air_company;
                               }else {
                                  $departure_journey->air_company = Fly_Constant::COMBINATION_AIR_COMPANY;         
                               }
                           }else {
                               $departure_journey->air_company = $departure_journey_air_company;
                           }
                           array_push($departure_journeys, $departure_journey);
                           array_push($departure_journeys_unique_keys, $unique_departure_journey_key);
                    }
                    
                   if(!$is_exist_return_journey && $return_journey != null){
                                              
                        $return_journey->key = $unique_return_journey_key;
                         if($departure_journey_air_company == $return_journey_air_company){
                             $return_journey->air_company = $return_journey_air_company;
                         }else{
                             $return_journey->air_company = Fly_Constant::COMBINATION_AIR_COMPANY;
                         }
                        
                        array_push($return_journeys, $return_journey);
                        array_push($return_journeys_unique_keys, $unique_return_journey_key);
                   }      
                 
                }
                if (count($departure_journeys) > 0) {
                    usort($departure_journeys, "self::journey_travel_time_compare2");
                }

                if (count($return_journeys) > 0) {
                    usort($return_journeys, "self::journey_travel_time_compare2");
                 }
                $combined_air_price_solution_item->departure_journeys = $departure_journeys;
                $combined_air_price_solution_item->return_journeys = $return_journeys;
                array_push($combined_air_price_solutions_array, $combined_air_price_solution_item);
                $count++;
            }
        
        
        return $combined_air_price_solutions_array;
    }

    // P1DT1H15M0.000S or PT1H15M0.000S seklinde gelmekte
    public function convert_journey_travel_time($travel_time) {
        $isDayFlag = strpos($travel_time, "D");
        $totalMinute = 0;
        if ($isDayFlag) {
            $day_count = substr($travel_time, $isDayFlag - 1, 1);
            $totalMinute = $totalMinute + intval($day_count) * 24 * 60;
        }
        $isTFlag = strpos($travel_time, "T");
        if ($isTFlag) {
            $hourFlag = strpos($travel_time, "H");
            $hour_count = substr($travel_time, $isTFlag + 1, $isTFlag + 1 - $hourFlag);
            $totalMinute = $totalMinute + intval($hour_count) * 60;
            $minuteFlag = strpos($travel_time, "M");
            $minute_count = substr($travel_time, $hourFlag + 1, $hourFlag + 1 - $minuteFlag);
            $totalMinute = $totalMinute + intval($minute_count);
        }
        return $totalMinute;
    }



    private function create_journey_uniqe_key($journey_air_segments_keys) {
        $unique_key = "";
        foreach ($journey_air_segments_keys as $air_segment_key) {
            $unique_key = $unique_key . $air_segment_key . ":";
        }
        return $unique_key;
    }

    private function isExsistAirsegmentKey($air_segment_keys, $key) {
        foreach ($air_segment_keys as $air_segment_key) {
            if ($air_segment_key == $key) {
                return TRUE;
            }
        }
        return FALSE;
    }

    private function gets_airsegment_by_keys($airsegment_keys, $air_segment_objects) {
        $found_airsegment_objects = array();
        foreach ($air_segment_objects as $air_segment_object) {
            foreach ($airsegment_keys as $airsegment_key) {
                if ($airsegment_key === $air_segment_object->key) {
                    array_push($found_airsegment_objects, $air_segment_object);
                }
            }
        }
        usort($found_airsegment_objects, 'self::air_segment_compare');
        return $found_airsegment_objects;
    }

    
    public  function get_airline_company_of_journey($journey){
          if($journey != null){
               $i = 0;
               $temp_airline_company ="";
              foreach($journey->air_segment_items as $air_segment_item){
                  if($i == 0){
                      $temp_airline_company = $air_segment_item->carrier;
                      $i++;
                  }else{
                      if($temp_airline_company == $air_segment_item->carrier){
                          $temp_airline_company = $air_segment_item->carrier;
                      }else{
                          return Fly_Constant::COMBINATION_AIR_COMPANY;
                      }
                  }
                  $i++;
              }
              return $temp_airline_company;
          }
          
         
    }

     private function set_booking_info_to_airsegment_project($air_price_info_items, $airsegment_object){
       // her bir air_price_solution 1 den fazla air_price_info içerebilir.
      $class = ""; 
      foreach ($air_price_info_items[0]->booking_short_info_array as $booking_info_object) {
        if ($booking_info_object->air_segment_ref === $airsegment_object->key) {
            $booking_counts = $airsegment_object->booking_counts;
            $booking_counts_array = explode("|", $booking_counts);

            $found = FALSE;
            foreach ($booking_counts_array as $book_code_info) {
                if ($booking_info_object->booking_code == substr($book_code_info, 0, 1)) {
                    $class = $book_code_info;
                    $avaible_booking_count = intval(substr($book_code_info, 1, 1));
                    $airsegment_object->avaible_booking_count =  $avaible_booking_count;
                    $airsegment_object->booking_code = $booking_info_object->booking_code;
                    $airsegment_object->booking_cabin_class = $booking_info_object->cabin_class;
                    /*
                    if ($avaible_booking_count < 9) {
                        $remain_book_count_warning_message = "(" . $avaible_booking_count . ")";
                    }
                     
                     */
                    $found = TRUE;
                  
                    break;
                }
            }
            if ($found == TRUE) {
                break;
            }
        }
     }
     return $airsegment_object;
   }
    public static function air_segment_compare($air_segment1, $air_segemnt2) {
        $ad = new DateTime($air_segment1->departure_time);
        $bd = new DateTime($air_segemnt2->departure_time);

        if ($ad == $bd) {
            return 0;
        }
        return $ad < $bd ? -1 : 1;
    }

    public static function journey_travel_time_compare2($journey1, $journey2) {
        if ($journey1->total_travel_time == $journey2->total_travel_time) {
            return 0;
        }
        return $journey1->total_travel_time < $journey2->total_travel_time ? -1 : 1;
    }

}

?>
